<template>
  <a-card>
    <a-tabs>
      <a-tab-pane key="orderdetail" :tab="$t('order_detail')">
        <a-page-header>
          <template slot="title">
            {{ orderDetail.distributor }}, {{ orderDetail.distributorOrderId }}
          </template>
          <template slot="extra">
            <a-button icon="reload" @click="fetchData" :loading="loading">
            </a-button>
          </template>
          <a-descriptions :column="3" bordered size="small">
            <a-descriptions-item :label="$t('selling_price')">
              <a-statistic :value="orderDetail.price">
                <template #suffix>
                  {{orderDetail.currency}}
                </template>
              </a-statistic>
            </a-descriptions-item>
            <a-descriptions-item :label="$t('order_status')">
              <a-tag :color="orderDetail.orderStatus === 10 || orderDetail.orderStatus === -10 ? 'blue':'red'">{{ $t("order_status_arr." + orderDetail.orderStatus)}}</a-tag>
              <a-tooltip>
                <template slot="title">
                  {{ $t('edit') }} {{ $t('order_status') }}
                </template>
                <a-button icon="edit" type="primary" size="small" @click="showUpdateOrderStatus"></a-button>
              </a-tooltip>
            </a-descriptions-item>
            <a-descriptions-item :label="$t('order_id')">
              {{ orderDetail.orderId }}
            </a-descriptions-item>
            <a-descriptions-item :label="$t('distributor')">
              <a @click="openDistributorHotel(orderDetail.distributor, orderDetail.hotelId)">{{ orderDetail.distributor }}</a>
            </a-descriptions-item>
            <a-descriptions-item :label="$t('distributor_order_id')">
              {{ orderDetail.distributorOrderId }}
            </a-descriptions-item>
            <a-descriptions-item :label="$t('distributor_order_status')">
              <a-tag :color="orderDetail.distributorOrderStatus === 10 || orderDetail.distributorOrderStatus === -10 ? 'blue':'red'">{{ $t("distributor_order_status_arr." + orderDetail.distributorOrderStatus)}}</a-tag>
              <a-tooltip>
                <template slot="title">
                  {{ $t('push') }} {{orderDetail.distributor}} {{ $t("distributor_order_status_arr.10") }}
                </template>
                <a-button icon="export" type="primary" size="small" @click="showPushSuccess"></a-button>
              </a-tooltip>
            </a-descriptions-item>
            <a-descriptions-item :label="$t('checkin')">
              <a-space><span>{{ orderDetail.checkin }}</span> ~ <span>{{ orderDetail.checkout }}</span></a-space>
            </a-descriptions-item>
            <a-descriptions-item :label="$t('cancel_time_limit')">
              {{ orderDetail.freeCancelTime }}
            </a-descriptions-item>
            <a-descriptions-item :label="$t('order_date')">
              {{ orderDetail.createdTime }}
            </a-descriptions-item>
            <a-descriptions-item :label="$t('hotel')" :span="3">
              <a-space>
                <a @click="openHotel(orderDetail.hotelId)">{{ orderDetail.hotelId }}</a> |
                <span>{{ hotelDetail.hotelNameEn }}</span> |
                <span>{{ hotelDetail.hotelNameCn }}</span>
                <a-rate :value="hotelDetail.hotelStar" disabled />
              </a-space>
            </a-descriptions-item>
            <a-descriptions-item :label="$t('address')" :span="3">
              <a-space>
                <span>{{ hotelDetail.cityName }}, {{ hotelDetail.countryName }}</span> |
                <span>{{ hotelDetail.hotelAddressEn }}</span> |
                <span>{{ hotelDetail.hotelAddressCn }}</span>
              </a-space>
            </a-descriptions-item>
            <a-descriptions-item :label="$t('room')" :span="2">
              {{ orderDetail.roomId }}.{{ orderDetail.roomName }}<a> X {{ orderDetail.roomCount }}</a>
            </a-descriptions-item>
            <a-descriptions-item :label="$t('meal_type')">
              {{ $t("meal_type_arr." + orderDetail.mealType)}} <a v-show="orderDetail.mealCount > 0">X {{ orderDetail.mealCount }}</a>
            </a-descriptions-item>
            <a-descriptions-item :label="$t('occupancy')">
              {{ this.guestRoom.Adults }}{{ $t("adult") }} <span v-if="this.guestRoom.Children > 0">{{ this.guestRoom.Children }}{{ $t("child") }}{{ this.guestRoom.ChildrenAges }}</span> <a v-if="this.guestRoom.Count > 1">X {{ this.guestRoom.Count }}</a>
            </a-descriptions-item>
            <a-descriptions-item :label="$t('guest_name')">
              <a-space>
                <template v-for="(item, index) in this.guestRoom.PaxNames">
                  <span :key="index">{{ item.FirstName }}/{{item.LastName}}</span>
                </template>
              </a-space>
              <div v-for="(arr, i) in this.guestRoom.GuestNames" :key="i">
                <a-space>
                  <span v-for="(item, j) in arr" :key="j">{{ item.FirstName }}/{{item.LastName}}</span>
                </a-space>
              </div>
            </a-descriptions-item>
            <a-descriptions-item :label="$t('hotel_confirm_no')">
              <a-space>
                <a-tag>{{ orderDetail.hotelConfirmNo }}</a-tag>
                <a-tooltip>
                  <template slot="title">
                    {{ $t('edit') + $t('hotel_confirm_no') }}
                  </template>
                  <a-button icon="edit" type="primary" size="small" @click="showUpdateConfirmNoForm"></a-button>
                </a-tooltip>
                <a-tooltip v-show="orderDetail.hotelConfirmNo !== undefined && orderDetail.hotelConfirmNo.length > 0">
                  <template slot="title">
                    {{ $t('push') }} {{orderDetail.distributor}} {{ $t('hotel_confirm_no') }}
                  </template>
                  <a-button icon="export" type="primary" size="small" @click="showPushHotelConfirmNo"></a-button>
                </a-tooltip>
              </a-space>
            </a-descriptions-item>
            <a-descriptions-item :label="$t('guest_note')" :span="2">
              {{ orderDetail.guestNote }}
            </a-descriptions-item>
            <a-descriptions-item label="RatePlan">
              {{ orderDetail.rateplanId }}
            </a-descriptions-item>
            <a-descriptions-item :label="$t('contacts')" :span="3">
              <a-space>
                <span>{{ orderDetail.contactName }}</span> <span>{{ orderDetail.contactPhone }}</span> <span>{{ orderDetail.contactEmail }}</span>
              </a-space>
            </a-descriptions-item>
          </a-descriptions>
        </a-page-header>
        <a-card :bordered="false" :title="$t('supplier_order')">
          <template #extra>
            <a-space v-if="false">
              <a-button type="primary" icon="plus" @click="showForm(null)">{{ $t('add') }}{{ $t('supplier_order') }}
              </a-button>
            </a-space>
          </template>

          <a-table size="small" :columns="columns" :data-source="orderSupplierList" :pagination="false" :row-key="record => record.id" :loading="loading" >
            <template slot="supplierHotelId" slot-scope="text, record">
              <a @click="openSupplierHotel(record.supplier,record.supplierHotelId)">{{ record.supplierHotelId }}</a>
            </template>
            <template slot="supplierOrderStatus" slot-scope="text">
              <a-tag :color="text === 10 || text === -10 ? 'blue':'red'">{{ $t("order_status_arr." + text)}}</a-tag>
            </template>
            <template slot="supplierRoomName" slot-scope="text, record">
              {{ record.supplierRoomId }} <br v-show="record.supplierRoomId.length > 0" /> {{ text }} <br /> {{ record.supplierRateplanId }}
            </template>
            <template slot="supplierPrice" slot-scope="text, record">
              {{ record.supplierCurrency }} {{ text }}
            </template>
            <template slot="supplierMealDesc" slot-scope="text, record">
              {{ text }} <a v-show="record.supplierMealCount > 0">X {{ record.supplierMealCount }}</a>
            </template>
            <template slot="action" slot-scope="text, record">
              <a-button icon="close" size="small" @click="showCancelOrder(record)" v-show="record.supplierOrderStatus >= 5 && record.supplierOrderId">{{ $t('cancel') }}</a-button>
            </template>
            <template slot="expandedRowRender" slot-scope="record">
              <div v-html="record.supplierRemark"></div>
              <a-button v-show="record.supplierExtrasJson.length > 2" @click="showExtrasData(record.supplierExtrasJson)">{{$t('extras_data')}}</a-button>
            </template>
            <template v-for="(item, index) in columns" :slot="item.slotName">
              <span :key="index">{{ $t(item.slotName) }}</span>
            </template>
          </a-table>
        </a-card>
      </a-tab-pane>
      <a-tab-pane key="log" :tab="$t('log')">
        <update-log ref="updateLog" :business-id="this.$route.params.orderId" :log-type="5" />
      </a-tab-pane>
    </a-tabs>

    <a-modal v-model="cancelOrderFormVisible" :maskClosable="false" :title="$t('cancel') + $t('supplier_order') + ': ' + this.supplierOrder.supplier + ', ' + this.supplierOrder.supplierOrderId" :confirm-loading="confirmLoading" :okText="$t('confirm')" @ok="cancelOrder()">
      <a-form-model ref="cancelOrderForm" layout="horizontal" :model="cancelOrderForm" autocomplete="off" :rules="cancelOrderFormRules">
        <a-form-model-item prop="logText">
          <a-textarea v-model="cancelOrderForm.logText" :auto-size="{ minRows: 3, maxRows: 10 }" :placeholder="$t('opt_remark')">
          </a-textarea>
        </a-form-model-item>
      </a-form-model>
    </a-modal>

    <a-modal v-model="updateConfirmNoFormVisible" :maskClosable="false" :title="$t('edit') + $t('hotel_confirm_no')" :confirm-loading="confirmLoading" :okText="$t('submit')" @ok="saveUpdateConfirmNo()">
      <a-form-model ref="updateConfirmNoForm" layout="horizontal" :model="updateConfirmNoForm" autocomplete="off">
        <a-form-model-item prop="logText">
          <a-input v-model="updateConfirmNoForm.hotelConfirmNo" :placeholder="$t('hotel_confirm_no')">
          </a-input>
        </a-form-model-item>
      </a-form-model>
    </a-modal>

    <a-modal v-model="updateOrderStatusFormVisible" :maskClosable="false" :title="$t('edit') + $t('order_status')" :confirm-loading="confirmLoading" :okText="$t('submit')" @ok="saveOrderStatus()">
      <a-form-model ref="updateOrderStatusForm" layout="horizontal" :model="updateOrderStatusForm" autocomplete="off" :rules="updateOrderStatusFormRules">
        <a-form-model-item prop="orderStatus">
          <a-select :options="updateOrderHotelStatusArr" v-model="updateOrderStatusForm.orderStatus"/>
        </a-form-model-item>
        <a-form-model-item prop="logText">
          <a-textarea v-model="updateOrderStatusForm.logText" :auto-size="{ minRows: 3, maxRows: 10 }" :placeholder="$t('opt_remark')">
          </a-textarea>
        </a-form-model-item>
      </a-form-model>
    </a-modal>

  </a-card>
</template>

<script>
import UpdateLog from '../updatelog/list'
import {getPublicData} from '@/services/public'
import {getDetail,updateOrderStatus,updateHotelConfirmNo,pushHotelConfirmNo,pushConfirmRoom} from '@/services/order'
import {cancelSupplierOrder} from '@/services/booking'

export default {
  name: "OrderDetail",
  components: { UpdateLog },
  i18n: require('../i18n'),
  data() {
    return {
      suppliers: [],
      orderHotelStatusArr: [],
      updateOrderHotelStatusArr: [],
      distributorStatusArr: [],
      supplierStatusArr: [],
      loading: false,
      orderDetail: {
        orderStatus:-20,
        distributorOrderStatus:-20,
        mealType:0,
      },
      orderSupplierList: [],
      hotelDetail: {},
      guestRoom: {},
      columns: [
        {
          dataIndex: 'supplier',
          align: 'center',
          slotName: "supplier",
          slots: { title: 'supplier' },
        },{
          dataIndex: 'supplierOrderId',
          align: 'left',
          slotName: "supplier_order_id",
          slots: {title: 'supplier_order_id'},
        },
        {
          dataIndex: 'supplierOrderStatus',
          align: 'center',
          slotName: "supplier_order_status",
          slots: {title: 'supplier_order_status'},
          scopedSlots: {customRender: 'supplierOrderStatus'},
        },
        {
          dataIndex: 'supplierPrice',
          align: 'left',
          slotName: "supplier_price",
          slots: {title: 'supplier_price'},
          scopedSlots: {customRender: 'supplierPrice'},
        },
        {
          dataIndex: 'supplierHotelId',
          align: 'center',
          slotName: "supplier_hotel_id",
          slots: { title: 'supplier_hotel_id' },
          scopedSlots: { customRender: 'supplierHotelId' },
        },{
          dataIndex: 'supplierRoomName',
          align: 'left',
          slotName: "room_name",
          slots: {title: 'room_name'},
          scopedSlots: { customRender: 'supplierRoomName' },
        },{
          dataIndex: 'supplierMealDesc',
          align: 'left',
          slotName: "meal_type",
          slots: {title: 'meal_type'},
          scopedSlots: { customRender: 'supplierMealDesc' },
        },{
          dataIndex: 'supplierFreeCancelTime',
          align: 'left',
          slotName: "cancel_time_limit",
          slots: {title: 'cancel_time_limit'},
        },{
          dataIndex: 'updatedTime',
          align:'center',
          slotName: "updatedTime",
          slots: { title: 'updatedTime' },
        },{
          align: 'center',
          slotName: "operation",
          slots: {title: 'operation'},
          scopedSlots: { customRender: 'action' },
        },
      ],
      confirmLoading: false,
      supplierOrder: {},
      cancelOrderFormVisible: false,
      cancelOrderForm: {},
      cancelOrderFormRules: {
        logText: [{required: true, trigger: 'blur',message:' '}],
      },
      updateConfirmNoFormVisible: false,
      updateConfirmNoForm: {},
      updateOrderStatusFormVisible: false,
      updateOrderStatusForm: {},
      updateOrderStatusFormRules: {
        logText: [{ required: true, trigger: 'blur',message: ' ' }],
      },
    }
  },
  methods: {
    getData() {
      getPublicData('sup_dis').then(res => {
        const {suppliers} = res.data
        this.suppliers.push({label: this.$t('supplier'), value: ''})
        suppliers.forEach(item => {
          this.suppliers.push({label: item, value: item, text: item})
        })
      }).catch(error => {
        console.log(error)
      })
    },
    fetchData(){
      this.loading = true
      getDetail(this.$route.params.orderId).then(res => {
        this.orderDetail = res.data.detail
        this.orderSupplierList = res.data.supplierList
        this.hotelDetail = res.data.hotelInfo
        this.guestRoom = JSON.parse(this.orderDetail.guestRoomJson)
        this.loading = false
      }).catch(error => {
        console.log(error)
        this.loading = false
      })
    },
    showExtrasData(json){
      const h = this.$createElement;
      this.$info({
        title: this.$t('extras_data'),
        content: h('div', {}, [
          h('code', json),
        ]),
        onOk() {},
      });
    },
    showCancelOrder(supplierOrder){
      this.supplierOrder = supplierOrder
      this.cancelOrderForm.orderId = supplierOrder.orderId
      this.cancelOrderForm.supplier = supplierOrder.supplier
      this.cancelOrderForm.supplierOrderId = supplierOrder.supplierOrderId
      this.cancelOrderForm.supplierExtrasJson = supplierOrder.supplierExtrasJson
      this.cancelOrderFormVisible = true
    },
    cancelOrder() {
      this.$refs.cancelOrderForm.validate(valid => {
        if (valid) {
          this.confirmLoading = true
          cancelSupplierOrder(this.cancelOrderForm).then(res => {
            if(res.data.success) {
              this.$message.success({content: this.$t('submitSuccess')})
              this.cancelOrderFormVisible = false
              this.fetchData()
            }else{
              this.$message.error({content: this.$t(res.data.message)})
            }
            this.confirmLoading = false
          }).catch(error => {
            console.log(error)
          })
        } else {
          return false;
        }
      });
    },
    saveUpdateConfirmNo(){
      this.confirmLoading = true
      updateHotelConfirmNo(this.updateConfirmNoForm).then(res => {
        if(res.data.success) {
          this.$message.success({content: this.$t('submitSuccess')})
          this.updateConfirmNoFormVisible = false
          this.fetchData()
        }else{
          this.$message.error({content: this.$t(res.data.message)})
        }
        this.confirmLoading = false
      }).catch(error => {
        console.log(error)
      })
    },
    saveOrderStatus() {
      this.$refs.updateOrderStatusForm.validate(valid => {
        if (valid) {
          this.confirmLoading = true
          updateOrderStatus(this.updateOrderStatusForm).then(res => {
            if(res.data.success) {
              this.$message.success({content: this.$t('submitSuccess')})
              this.updateOrderStatusFormVisible = false
              this.fetchData()
            }else{
              this.$message.error({content: this.$t(res.data.message)})
            }
            this.confirmLoading = false
          }).catch(error => {
            console.log(error)
          })
        } else {
          return false;
        }
      });
    },
    showPushHotelConfirmNo(){
      let self = this
      this.$confirm({
        title: this.$t('push') + ' ' + this.orderDetail.distributor + ' ' + this.$t('hotel_confirm_no'),
        content: this.orderDetail.hotelConfirmNo,
        onOk() {
          pushHotelConfirmNo({orderId: self.orderDetail.orderId}).then(res => {
            if(res.data.success) {
              self.$message.success({content: self.$t('submitSuccess')})
            }else{
              self.$message.error({content: self.$t(res.data.message)})
            }
          }).catch(error => {
            console.log(error)
          })
        },
      });
    },
    showPushSuccess() {
      let self = this
      this.$confirm({
        title: this.$t('push') + ' ' + this.orderDetail.distributor + ' ' + this.$t('distributor_order_status_arr.10'),
        onOk() {
          pushConfirmRoom({orderId: self.orderDetail.orderId}).then(res => {
            if(res.data.success) {
              self.$message.success({content: self.$t('submitSuccess')})
            }else{
              self.$message.error({content: self.$t(res.data.message)})
            }
          }).catch(error => {
            console.log(error)
          })
        },
        onCancel() {
          console.log('Cancel');
        },
        class: 'test',
      });
    },
    showUpdateConfirmNoForm(){
      this.updateConfirmNoFormVisible = true
      this.updateConfirmNoForm = {
        orderId: this.orderDetail.orderId,
        hotelConfirmNo: this.orderDetail.hotelConfirmNo,
      }
    },
    showUpdateOrderStatus(){
      this.updateOrderStatusFormVisible = true
      this.updateOrderStatusForm = {
        orderId: this.orderDetail.orderId,
        orderStatus: this.orderDetail.orderStatus,
      }
    },
    openHotel(hotelId){
      this.$openPage('/hotel/detail/' + hotelId, "[" + hotelId + "]")
    },
    openDistributorHotel(distributor, hotelId){
      if(distributor === 'other')
        return

      this.$openPage('/distributor/detail/' + distributor + '/' + hotelId, "[" + distributor + "][" + hotelId + "]")
    },
    openSupplierHotel(supplier, supplierHotelId){
      this.$openPage('/supplier/hotel/' + supplier + '/' + supplierHotelId, "[" + supplier + "][" + supplierHotelId + "]")
    },
  },
  created() {
    this.getData()
    this.fetchData()
    this.orderHotelStatusArr = [
      {label:this.$t("order_status"), value:''},
      {label:this.$t("order_status_arr.10"), value:10},
      {label:this.$t("order_status_arr.5"), value:5},
      {label:this.$t("order_status_arr.0"), value:0},
      {label:this.$t("order_status_arr.-10"), value:-10},
      {label:this.$t("order_status_arr.-20"), value:-20},
    ]
    this.updateOrderHotelStatusArr = [
      {label:this.$t("order_status_arr.10"), value:10},
      {label:this.$t("order_status_arr.5"), value:5},
      {label:this.$t("order_status_arr.-10"), value:-10},
      {label:this.$t("order_status_arr.-20"), value:-20},
    ]
    this.distributorStatusArr = [
      {label:this.$t("distributor_order_status"), value:''},
      {label:this.$t("distributor_order_status_arr.10"), value:10},
      {label:this.$t("distributor_order_status_arr.5"), value:5},
      {label:this.$t("distributor_order_status_arr.-10"), value:-10},
      {label:this.$t("distributor_order_status_arr.-20"), value:-20},
    ]
    this.supplierStatusArr = [
      {label:this.$t("supplier_order_status"), value:''},
      {label:this.$t("order_status_arr.10"), value:10},
      {label:this.$t("order_status_arr.5"), value:5},
      {label:this.$t("order_status_arr.0"), value:0},
      {label:this.$t("order_status_arr.-10"), value:-10},
      {label:this.$t("order_status_arr.-20"), value:-20},
    ]
  },
}
</script>

<style scoped>

</style>